#include <iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode *deleteDuplicates(ListNode *head) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    if(!head)
        return NULL;

    ListNode *pHead = new ListNode(0);
    ListNode *pWrite = pHead;
    ListNode *pRead = head;
    int curCount = 0;
    ListNode *pStartNode = head;
    while(pRead){
        if(pRead->val != pStartNode->val){
            // end of last node
            if(curCount == 1){
                pWrite->next = pStartNode;
                pWrite = pWrite->next;
            }
            // reset
            curCount = 1;
            pStartNode = pRead;
        }
        else{
            ++curCount;
        }
        pRead = pRead->next;
    }
    // last one
    if(curCount == 1){
        pWrite->next = pStartNode;
        pWrite = pWrite->next;
    }
    pWrite->next = NULL;

    pRead = pHead->next;
    delete pHead;
    return pRead;
}